import 'package:async/async.dart';
import 'package:boss/common/common.dart';


import 'package:boss/main.dart';
import 'package:boss/models/cloud_printer.dart';
import 'package:boss/models/printer_bill_style.dart';
import 'package:boss/models/store_area.dart';
import 'package:boss/models/store_menu.dart';
import 'package:boss/provider/cloud_printer_provider.dart';
import 'package:boss/provider/commodity_provider.dart';
import 'package:boss/provider/table_provider.dart';
import 'package:boss/ui/page/printer/constant/printer_constant.dart';
import 'package:boss/ui/page/printer/page/printerStepTwo/modal/picker_bill_style_modal.dart';
import 'package:boss/ui/page/printer/page/printerStepTwo/modal/picker_commodity_modal.dart';
import 'package:boss/ui/widget/button/fixed_bottom_btn.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/radioList/model/radio_item_data.dart';
import 'package:boss/ui/widget/radioList/radio_list_picker.dart';
import 'package:boss/ui/widget/title_row_button.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class PrinterStepTwoBrowser extends StatefulWidget {
  final int id;

  const PrinterStepTwoBrowser(this.id);

  @override
  _PrinterStepTwoBrowserState createState() => _PrinterStepTwoBrowserState();
}

class _PrinterStepTwoBrowserState extends State<PrinterStepTwoBrowser> {
  List<SelectItem<int>> printerTypes = [
//  SelectItem(title: '全部', value: PrinterConstant.ALL_PRINTER),
    SelectItem(title: '前台打印机', value: PrinterConstant.FRONT_PRINTER),
    SelectItem(title: '后厨打印机', value: PrinterConstant.KITCHEN_PRINTER),
//    SelectItem(title: '标签打印机', value: PrinterConstant.TAG_PRINTER),
  ];

  List<SelectItem<int>> cutTypes = [
    SelectItem(title: '不切单', value: PrinterConstant.NO_CUT_ORDER),
    SelectItem(title: '一菜一切', value: PrinterConstant.CUT_ORDER),
  ];

  List<SelectItem<int>> orderByTypes = [
    SelectItem(title: '按照菜品分类打印', value: PrinterConstant.ORDER_BY_MENU),
    SelectItem(title: '按下单时间顺序打印', value: PrinterConstant.ORDER_BY_TIME),
  ];

  List<RadioItemData<StoreArea>> areas = [];

  List<StoreMenu> menus = [];

  List<PrinterBillStyle> styles = [];

  pickStoreArea() async {
    var provider = Provider.of<CloudPrinterProvider>(
      context,
      listen: false,
    );
    List<StoreArea> defaultValue = [];

    provider.editCloudPrinter.printerPlanAreaList?.forEach((item) {
      var find = areas.firstWhere((area) => area.value.areaId == item.areaId, orElse: () => null);
      if (find != null) {
        defaultValue.add(find.value);
      }
    });

    var selected = await showRadioListPicker<StoreArea>(
      context,
      items: areas,
      title: '选择区域',
      isMultiple: true,
      value: defaultValue,
    );

    if (selected != null) {
      provider.setArea(selected);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Loader(
      loadTask: loadTask,
      builder: (context) => Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(
                  horizontal: 30.w,
                ),
                child: Consumer<CloudPrinterProvider>(
                  builder: (context, provider, child) => Column(
                    children: <Widget>[
                      SelectFormField(
                        title: '选择打印类型',
                        isRequired: true,
                        items: printerTypes,
                        onChanged: (value) {
                          provider.setType(value, styles);
                        },
                        value: provider.editCloudPrinter.type,
                      ),

                      //前台打印机  隐藏打印那些菜品
                      if (provider.editCloudPrinter.type != PrinterConstant.FRONT_PRINTER)
                        TitleRowButton(
                          title: '打印哪些菜品',
                          isRequired: true,
                          hintText: '请选择',
                          onTap: () async {
                            var res = await showPickerCommodityModal(
                              context,
                              selected: provider.editCloudPrinter.printerPlanFoodList?.map((item) => item.commodityId)?.toList(),
                              menus: menus,
                            );
                            if (res != null) {
                              provider.setCommoditys(res);
                            }
                          },
                          value: provider.editCloudPrinter.printerPlanFoodList.length >= menus[0].commodityList.length
                              ? '全部菜品'
                              : provider.editCloudPrinter.printerPlanFoodListText,
                        ),
                      TitleRowButton(
                        title: '打印票据与份数',
                        isRequired: true,
                        hintText: '请选择',
                        value: provider.editCloudPrinter.printerPlanBillListText,
                        onTap: () async {
                          var res = await pickerBillStyleModal(context, provider.editCloudPrinter.printerPlanBillList);
                          if (res != null) {
                            provider.setPrinterPlanBillList(res);
                          }
                        },
                      ),
                      //后厨打印机  隐藏 打印桌台区域
                      if (provider.editCloudPrinter.type != PrinterConstant.KITCHEN_PRINTER)
                        TitleRowButton(
                          title: '打印桌台区域',
                          hintText: '请选择',
                          value:
                              provider.editCloudPrinter.printerPlanAreaList.length >= areas.length ? '全部区域' : provider.editCloudPrinter.printerPlanAreaListText,
                          onTap: pickStoreArea,
                        ),
                      SelectFormField(
                        title: '切单方式',
                        items: cutTypes,
                        value: provider.editCloudPrinter.cutType,
                        onChanged: (value) {
                          provider.setCutType(value);
                        },
                      ),
                      SelectFormField(
                        title: '菜品展示顺序',
                        items: orderByTypes,
                        value: provider.editCloudPrinter.orderByType,
                        onChanged: (value) {
                          provider.setOrderByType(value);
                        },
                      ),
                    ],
                  ),
                )),
          ),
          FixedBottomBtn(
            title: '保存',
            onTap: () {
              var provider = Provider.of<CloudPrinterProvider>(
                context,
                listen: false,
              );
              provider.isEdit ? provider.updateCloudPrinter() : provider.addCloudPrinter();
            },
          ),
        ],
      ),
    );
  }

  Future<Result> loadTask() async {
    if (widget.id != null) {
      var provider = Provider.of<CloudPrinterProvider>(
        context,
        listen: false,
      );
      var detaile = await provider.getCloudPrinterById(widget.id);
      if (detaile.isError) {
        return detaile;
      }
    }

    var res = await Future.wait([loadStoreArea(), loadStoreCommodity(), loadBillStyles()]);

    return res[0] && res[1] && res[2] ? Result.value(null) : Result.error(Constant.httpErrText);
  }

  Future<bool> loadStoreArea() async {
    try {
      var res = await Provider.of<TableProvider>(
        context,
        listen: false,
      ).initData();

      if (res.isError) {
        return false;
      }

      areas = res.asValue.value
          .map((item) => RadioItemData(
                title: item.areaName,
                value: item,
              ))
          .toList();

      var cloudPrinterProvider = Provider.of<CloudPrinterProvider>(
        context,
        listen: false,
      );
      if (!cloudPrinterProvider.isEdit)
        cloudPrinterProvider.editCloudPrinter.printerPlanAreaList = areas
            .map((item) => PrinterPlanAreaList.fromJson({
                  'areaId': item.value.areaId,
                  'areaName': item.value.areaName,
                }))
            .toList();

      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> loadStoreCommodity() async {
    var provider = Provider.of<CommodityProvider>(
      context,
      listen: false,
    );

    var res = await provider.initData();
    if (res.isError) {
      return false;
    }

    menus = res.asValue.value.where((item) => item.commodityList.length > 0).toList();

    var allMenu = StoreMenu.fromJson({
      'menuId': -1,
      'menuName': '全部',
      'commodityList': [],
    });

    menus.forEach((item) {
      allMenu.commodityList.addAll(item.commodityList);
    });

    menus.insert(0, allMenu);

    var cloudPrinterProvider = Provider.of<CloudPrinterProvider>(
      context,
      listen: false,
    );
    if (!cloudPrinterProvider.isEdit)
      cloudPrinterProvider.editCloudPrinter.printerPlanFoodList = menus[0]
          .commodityList
          .map((item) => PrinterPlanFoodList.fromJson({
                'commodityId': item.id,
                'commodityName': item.title,
                'menuId': item.menuId,
                'menuName': item.menuName,
              }))
          .toList();

    return true;
  }

  Future<bool> loadBillStyles() async {
    try {
      var res = await api.queryPrinterBillList();
      if (!res.successful()) {
        return false;
      }

      styles = res.data;

      var cloudPrinterProvider = Provider.of<CloudPrinterProvider>(
        context,
        listen: false,
      );

      if (!cloudPrinterProvider.isEdit)
        cloudPrinterProvider.editCloudPrinter.printerPlanBillList = styles
            .map((item) => PrinterPlanBillList.fromJson({
                  'billName': item.billName,
                  'count': 1,
                  'printerBillId': item.id,
                  'type': item.type,
                }))
            .toList();

      return true;
    } catch (e) {
      return false;
    }
  }
}
